<?php

namespace app\controllers;

use yii\db\Query;
use yii\web\Controller;


class WxappController extends AdminBaseController {

      //小程序配置
     public function actionIndex(){
         if($this->post()){
         $data=\Yii::$app->request->post();
         $res=\Yii::$app->db->createCommand()->update('yii_wxapp',$data)->execute();
         if ($res){
             return json_encode(['code'=>1,'msg'=>'更新成功']);
         }else{
             return json_encode(['code'=>0,'msg'=>'无数据更新']);
            }
         }
         $wxapp=(new Query())->select('*')->from('yii_wxapp')->one();
         return $this->render('index',['wxapp'=>$wxapp]);
       }

    //轮播图
    public function actionBanner(){
         $list=(new Query())->select('*')->from('yii_banner')->orderBy('sort')->all();
         foreach ($list as $k=>$v){
             $list[$k]['img']=$this->GetImg($v['img_id']);
         }
         return $this->render('banner',['list'=>$list]);
    }

    //添加轮播图
    public function actionAddbanner(){
         if ($this->post()){
             $data=\Yii::$app->request->post();
             unset($data['imageFile']);
             $res=\Yii::$app->db->createCommand()->insert('yii_banner',$data)->execute();
             if ($res){
                 return json_encode(['code'=>1,'msg'=>'添加成功']);
             }else{
                 return json_encode(['code'=>0,'msg'=>'添加失败']);
             }
         }
     return $this->render('addbanner');
    }

    //编辑轮播图
    public function actionEditbanner(){
        if ($this->post()){
            $data=\Yii::$app->request->post();
            unset($data['imageFile']);
            $res=\Yii::$app->db->createCommand()->update('yii_banner',$data,array('id'=>$data['id']))->execute();
            if ($res){
                return json_encode(['code'=>1,'msg'=>'更新成功']);
            }else{
                return json_encode(['code'=>0,'msg'=>'无数据更新']);
            }
        }else{
            $id=$this->GetId();
            $list=(new Query())->select('*')->from('yii_banner')->where(array('id'=>$id))->one();
            $list['img']=$this->GetImg($list['img_id']);
        }

        return $this->render('editbanner',['list'=>$list]);
    }

    //删除轮播图
    public function actionDelbaner(){
         $id=$this->PostId();
         $transaction = \Yii::$app->db->beginTransaction();
         try {
             $info=(new Query())->select('*')->from('yii_banner')->where(array('id'=>$id))->one();
              $this->DelFile($info['img_id']);
              $this->DelPicture($info['img_id']);
             \Yii::$app->db->createCommand()->delete('yii_banner',array('id'=>$id))->execute();
             $transaction->commit();
             return json_encode(['code'=>1,'msg'=>'删除成功']);
         } catch (\Exception $e) {
            $transaction->rollBack();
             return json_encode(['code'=>0,'msg'=>'删除失败']);
        }
    }



}
